package com.ktjy.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class HelloFilter implements Filter {
    //初始化
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter init");
        Filter.super.init(filterConfig);
    }
    //判断是否继续
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.out.println("doFilter...执行前");
        String requestURI = request.getRequestURI();
        if(requestURI.endsWith("/login") || requestURI.endsWith("/go") ){
            filterChain.doFilter(request, servletResponse);
        }
        Object obj=request.getSession().getAttribute("user");
        if(obj==null) {
            request.getRequestDispatcher("login").forward(request,servletResponse);
        }
        filterChain.doFilter(request, servletResponse);
        System.out.println("doFilter...执行后");

    }
    //销毁
    @Override
    public void destroy() {
        System.out.println("Filter destroy");
        Filter.super.destroy();
    }
}
